/*
 * Funambol is a mobile platform developed by Funambol, Inc. 
 * Copyright (C) 2008 Funambol, Inc.
 * 
 * This program is free software; you can redistribute it and/or modify it under
 * the terms of the GNU Affero General Public License version 3 as published by
 * the Free Software Foundation with the addition of the following permission 
 * added to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED
 * WORK IN WHICH THE COPYRIGHT IS OWNED BY FUNAMBOL, FUNAMBOL DISCLAIMS THE 
 * WARRANTY OF NON INFRINGEMENT  OF THIRD PARTY RIGHTS.
 * 
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
 * FOR A PARTICULAR PURPOSE.  See the GNU General Public License for more
 * details.
 * 
 * You should have received a copy of the GNU Affero General Public License 
 * along with this program; if not, see http://www.gnu.org/licenses or write to
 * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
 * MA 02110-1301 USA.
 * 
 * You can contact Funambol, Inc. headquarters at 643 Bair Island Road, Suite 
 * 305, Redwood City, CA 94063, USA, or at email address info@funambol.com.
 * 
 * The interactive user interfaces in modified source and object code versions
 * of this program must display Appropriate Legal Notices, as required under
 * Section 5 of the GNU Affero General Public License version 3.
 * 
 * In accordance with Section 7(b) of the GNU Affero General Public License
 * version 3, these Appropriate Legal Notices must retain the display of the
 * "Powered by Funambol" logo. If the display of the logo is not reasonably 
 * feasible for technical reasons, the Appropriate Legal Notices must display
 * the words "Powered by Funambol".
 */

#include "base/fscapi.h"
#include "base/debug.h"
#include "base/errors.h"
#include "base/Log.h"
#include "base/globalsdef.h"
#include "base/util/utils.h"

#include "iPhoneDefaultConfigFactory.h"
#import <UIKit/UIKit.h>

USE_NAMESPACE


iPhoneDefaultConfigFactory::iPhoneDefaultConfigFactory() {
}

iPhoneDefaultConfigFactory::~iPhoneDefaultConfigFactory() {
}


AccessConfig* iPhoneDefaultConfigFactory::getAccessConfig() {

    AccessConfig* ac = new AccessConfig();

    ac->setUsername             ("");
    ac->setPassword             ("");
    ac->setFirstTimeSyncMode    (SYNC_NONE);
    ac->setUseProxy             (false);
    ac->setProxyHost            ("");
    ac->setProxyPort            (8080);
    ac->setProxyUsername        ("");
    ac->setProxyPassword        ("");
    ac->setSyncURL              ("http://my.funambol.com/sync");
    ac->setBeginSync            (0);
    ac->setEndSync              (0);
    ac->setServerAuthRequired   (false);
    ac->setClientAuthType       ("syncml:auth-basic");
    ac->setServerAuthType       ("syncml:auth-basic");
    ac->setServerPWD            ("funambol");
    ac->setServerID             ("funambol");
    ac->setServerNonce          ("");
    ac->setClientNonce          ("");
    ac->setMaxMsgSize           (16000);
    ac->setReadBufferSize       (0);
    StringBuffer ua("Funambol iPhone Plug-in ");
    ua.append([[[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleVersion"] UTF8String]);
    ac->setUserAgent            (ua.c_str());
    ac->setCheckConn            (true);
    ac->setResponseTimeout      (0);
    //ac->setEncryption           (false);

    return ac;
}



DeviceConfig* iPhoneDefaultConfigFactory::getDeviceConfig() {

    DeviceConfig* dc = new DeviceConfig();
    
    UIDevice* UUID = [[UIDevice alloc] init];
    StringBuffer deviceId;
    if([UUID.model isEqualToString:@"iPhone"]){
        deviceId = "iph-";
    }else if([UUID.model isEqualToString:@"iPod"]){
        deviceId = "ipt-";
    }else{
        deviceId = "iph-";
    }
    char base64      [64];
    char digest      [16];
    memset(digest,      0, 16);
    memset(base64,      0, 64);
    
    calculateMD5([UUID.uniqueIdentifier UTF8String], strlen([UUID.uniqueIdentifier UTF8String]), digest);
    b64_encode((char*)base64, digest, 16);
    
    deviceId.append(base64);
    
    [UUID release];
    

    dc->setMan                  ("Funambol Inc.");
    dc->setMod                  ("iPhone");
    dc->setOem                  ("Open Source");
    dc->setFwv                  ("");
    dc->setSwv                  ("");
    dc->setHwv                  ("");
    dc->setDevID                (deviceId.c_str());
    dc->setDevType              ("iPhone");
    dc->setDsV                  ("");
    dc->setUtc                  (true);
    dc->setLoSupport            (false);
    dc->setNocSupport           (true);
    dc->setLogLevel             (LOG_LEVEL_INFO);
    LOG.setLevel                (LOG_LEVEL_INFO);
    dc->setMaxObjSize           (2000000);
    dc->setDevInfHash           ("");

    return dc;
}



SyncSourceConfig* iPhoneDefaultConfigFactory::getSyncSourceConfig(const char* name) {

    SyncSourceConfig* sc = new SyncSourceConfig();

    sc->setName                 (name);
    sc->setSync                 ("two-way");
    sc->setSyncModes            ("slow,two-way,one-way-from-server,one-way-from-client");
    sc->setLast                 (0);
    sc->setEncryption           ("");

    if (!strcmp(name, "addressbook")){
        sc->setEncoding         ("bin");
        sc->setURI              ("card");
        sc->setSupportedTypes   ("text/x-vcard");
        sc->setType             ("text/x-vcard");
        sc->setVersion          ("2.1");
    }
    
    else if (!strcmp(name, "calendar")){
        sc->setEncoding         ("bin");
        sc->setURI              ("event");
        sc->setSupportedTypes   ("text/x-vcalendar");
        sc->setType             ("text/x-vcalendar");
        sc->setVersion          ("1.0");

    }
    /*else if (!strcmp(name, "task")){
        sc->setURI              ("stask");
        sc->setType             ("text/x-s4j-sift");
    }*/
    else if (!strcmp(name, "note")){
        sc->setEncoding         ("b64");
        sc->setURI              ("snote");
        sc->setSupportedTypes   ("text/x-s4j-sifn");
        sc->setType             ("text/x-s4j-sifn");
        sc->setVersion          ("1.1");

    }
    

    // *** TBD ***
    //sc->setCtCap

    return sc;
}

int getBuildNumberFromVersion(const char* swv) {
    
    int major=0, minor=0, build=0;
    if (!swv) {
        return 0;
    }
    
    sscanf(swv, "%d.%d.%d", &major, &minor, &build);
    return (major*10000 + minor*100 + build);
}

void iPhoneDefaultConfigFactory::upgrade(DMTClientConfig* clientconfig){
    const char* settingsversion= clientconfig->getDeviceConfig().getSwv();
    if( strcmp(settingsversion, "") == 0 ){
        
        //Access Config changes
        StringBuffer ua("Funambol iPhone Plug-in ");
        ua.append([[[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleVersion"] UTF8String]);
        clientconfig->getAccessConfig().setUserAgent            (ua.c_str());
        clientconfig->getDeviceConfig().setSwv([[[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleVersion"] UTF8String]);
        //Device Config changes
        
        UIDevice* UUID = [[UIDevice alloc] init];
        StringBuffer deviceId;
        if([UUID.model isEqualToString:@"iPhone"]){
            deviceId = "iph-";
        }else if([UUID.model isEqualToString:@"iPod"]){
            deviceId = "ipt-";
        }else{
            deviceId = "iph-";
        }
        char base64      [64];
        char digest      [16];
        memset(digest,      0, 16);
        memset(base64,      0, 64);
        
        calculateMD5([UUID.uniqueIdentifier UTF8String], strlen([UUID.uniqueIdentifier UTF8String]), digest);
        b64_encode((char*)base64, digest, 16);
        
        deviceId.append(base64);
        
        [UUID release];
        
        clientconfig->getDeviceConfig().setDevID                (deviceId.c_str());
        clientconfig->getDeviceConfig().setMaxObjSize           (2000000);
        
        //Addressbook SyncSource Config changes
        
        SyncSourceConfig* sc = clientconfig->getSyncSourceConfig("addressbook");
        sc->setSyncModes            ("slow,two-way,one-way-from-server,one-way-from-client");  
        sc->setSync                 ("two-way");
        sc->setEncoding         ("bin");
        sc->setSupportedTypes   ("text/x-vcard");
        
        clientconfig->setSyncSourceConfig(*sc);
        clientconfig->save();
    }
    
    
    
} 